﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HaiHui.Business;
using System.Threading;
using System.Diagnostics;
using System.Net;
using Microsoft.Win32;
using System.IO;
using HaiHui.Data;

namespace HaiHui
{
    /// <summary>
    /// Interaction logic for PictureDetail.xaml
    /// </summary>
    public partial class PictureDetail : UserControl
    {
        public enum DisplayMode
        {
            Picture,
            Nothing, 
            NewPicture
        }

        public void AddNewPhoto(Object sender, EventArgs e)
        {
            DisplayModeProp = DisplayMode.Nothing;
            DisplayModeProp = DisplayMode.NewPicture;
        }


        private DisplayMode m_DisplayMode;
        public DisplayMode DisplayModeProp
        {
          get { return m_DisplayMode; }
          set 
          { 
              m_DisplayMode = value; 

              if (m_DisplayMode == DisplayMode.Nothing)
              {
                stackNewPictures.Visibility = Visibility.Collapsed;
                imgSmallImage.Source = m_DefaultSmallImage;

                imgLarge.Visibility = Visibility.Collapsed;

                cmbAlbum.SelectedIndex = -1;
                txtPictureName.Clear();
                txtDescriere.Clear();
                txtCuvinteCheie.Clear();
                chkAcceptaComentarii.IsChecked = false;
                chkPublica.IsChecked = false;
              }
              else if (m_DisplayMode == DisplayMode.Picture)
              {
                  stackNewPictures.Visibility = Visibility.Collapsed;
                  imgSmallImage.Source = m_Picture.SmallImage;
                  imgLarge.Visibility = Visibility.Visible;
                  imgLarge.BeginInit();
                  imgLarge.Width = m_Picture.LargeImage.Width;
                  imgLarge.Height = m_Picture.LargeImage.Height;
                  imgLarge.Source = m_Picture.LargeImage;
                  imgLarge.EndInit();

                  cmbAlbum.SelectedValue = m_Picture.Album;

                  txtPictureName.Text = m_Picture.Name;
                  txtDescriere.Text = m_Picture.Descriere;
                  txtCuvinteCheie.Text = m_Picture.CuvinteCheie;
                  chkAcceptaComentarii.IsChecked = m_Picture.AcceptaComentarii;
                  chkPublica.IsChecked = m_Picture.Public;
              }
              else if (m_DisplayMode == DisplayMode.NewPicture)
              {
                  stackNewPictures.Visibility = Visibility.Visible;

                  m_NewPictures = new List<string>();
              }
          }
        }

        private List<String> m_NewPictures= new List<string>();
        public List<String> NewPictures
        {
            get
            {
                return m_NewPictures;
            }
        }

        private Picture m_Picture;
        public Picture Picture
        {
            set
            {
                m_Picture = value;
                LoadPictureData();    
            }
        }

        private ImageSource m_DefaultSmallImage;

        public PictureDetail()
        {
            InitializeComponent();
            m_DefaultSmallImage = imgSmallImage.Source;

            cmbAlbum.ItemsSource = DataStore.Albums;
            cmbAlbum.DisplayMemberPath = "Name";
        }

        private void LoadPictureData()
        {
            if (m_Picture == null)
            {
                DisplayModeProp = DisplayMode.Nothing;
            }
            else
            {
                DisplayModeProp = DisplayMode.Picture;
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            imgLarge.Width = 0;
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            #region Validations
            if (lvNewImages.Items.Count == 0)
            {
                MessageBox.Show("Nicio imagine de adaugat!", "HaiHui", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (cmbAlbum.SelectedIndex == -1)
            {
                MessageBox.Show("Alege un album!", "HaiHui", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (txtPictureName.Text.Trim().Length == 0)
            {
                MessageBox.Show("Lipseste numele pozei!", "HaiHui", MessageBoxButton.OK, MessageBoxImage.Warning);
                txtPictureName.Clear();
                txtPictureName.Focus();
                return;
            }
            if (txtDescriere.Text.Trim().Length == 0)
            {
                MessageBox.Show("Lipseste descrierea pozei!", "HaiHui", MessageBoxButton.OK, MessageBoxImage.Warning);
                txtDescriere.Clear();
                txtDescriere.Focus();
                return;
            }
            if (txtCuvinteCheie.Text.Trim().Length == 0)
            {
                MessageBox.Show("Lipsesc cuvintele-cheie!", "HaiHui", MessageBoxButton.OK, MessageBoxImage.Warning);
                txtCuvinteCheie.Clear();
                txtCuvinteCheie.Focus();
                return;
            }
            #endregion


            string urlToSubmitForm = String.Empty;

            if (m_DisplayMode == DisplayMode.Picture)
            {
                urlToSubmitForm = String.Concat(Constants.PictureDetailsBaseURL, m_Picture.Id.ToString());
            }
            else if (m_DisplayMode == DisplayMode.NewPicture)
            {
                urlToSubmitForm = Constants.AddNewPictureURL;
            }

            Dictionary<String, String> parameters = new Dictionary<string, string>();
            parameters.Add("id_album", ((Album)cmbAlbum.SelectedValue).Id.ToString());
            parameters.Add("nume", txtPictureName.Text);
            parameters.Add("descriere", txtDescriere.Text);
            parameters.Add("tags", txtCuvinteCheie.Text);
            parameters.Add("accept_comentarii", (chkAcceptaComentarii.IsChecked == true) ? "1" : "0");
            parameters.Add("activ", (chkPublica.IsChecked == true) ? "1" : "0");
            parameters.Add("inregistreaza.x", "53");
            parameters.Add("inregistreaza.y", "7");

            try
            {

                string[] filesToUpload;
                if (m_DisplayMode == DisplayMode.Picture)
                    filesToUpload = new String[] { };
                else
                {
                    filesToUpload = (from pics in lvNewImages.Items.OfType<String>()
                                     select (string)pics).ToArray();
                }

                for (int i = 0; i < filesToUpload.Length; i++)
                {
                    Dictionary<String, String> parameters2 = new Dictionary<string, string>();
                    parameters.Keys.ToList().ForEach(p => { parameters2.Add(p, parameters[p]); });

                    if (filesToUpload.Length > 1)
                    {
                        parameters2["nume"] = parameters2["nume"] + String.Format("({0})", i + 1);
                        parameters2["descriere"] = parameters2["descriere"] + String.Format("({0})", i + 1);
                    }
                    HttpUtils.SendPOSTWithFile(
                        urlToSubmitForm, 
                        filesToUpload[i], 
                        parameters2);
                }
            }
            catch (Exception ex)
            {

            }

        }

        private void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            m_Picture.GetDetailsData();
            DisplayModeProp = m_DisplayMode;
        }

        private void btnAddPicture_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDlg = new OpenFileDialog();
            openFileDlg.Multiselect = true;
            openFileDlg.Filter = "JPG Files|*.jpg|JPEG Files|*.jpeg";
            if (openFileDlg.ShowDialog() == true)
            {

                foreach (string fileName in openFileDlg.FileNames)
                    lvNewImages.Items.Add(fileName);
                
            }
        }

        private void lvNewImages_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                foreach (string s in lvNewImages.SelectedItems.OfType<String>().ToArray())
                {
                    lvNewImages.Items.Remove(s);
                }
            }
        }
    }
}
